package com.ruoyi.common.pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.business.dao.YytAttrGroupMapper;
import com.ruoyi.common.business.entity.YytAttrGroup;
import com.ruoyi.common.oms.dao.YytOmsCartItemMapper;
import com.ruoyi.common.oms.dao.YytOmsOrderItemMapper;
import com.ruoyi.common.oms.entity.YytOmsCartItem;
import com.ruoyi.common.oms.entity.YytOmsOrderItem;
import com.ruoyi.common.pms.dao.YytPmsSkuSaleAttrValueMapper;
import com.ruoyi.common.pms.dao.YytPmsSpuAttrValueMapper;
import com.ruoyi.common.pms.entity.*;
import com.ruoyi.common.pms.dao.YytPmsSkuInfoMapper;
import com.ruoyi.common.pms.service.YytPmsSkuImagesService;
import com.ruoyi.common.pms.service.YytPmsSkuInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.pms.service.YytPmsSpuImagesService;
import com.ruoyi.common.sms.entity.YytSmsCoupon;
import com.ruoyi.common.sms.service.YytSmsCouponHistoryService;
import com.ruoyi.vo.ClassBySkuInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * sku信息 服务实现类
 * </p>
 *
 * @author huangshun
 * @since 2021-12-16
 */
@Service
public class YytPmsSkuInfoServiceImpl extends ServiceImpl<YytPmsSkuInfoMapper, YytPmsSkuInfo> implements YytPmsSkuInfoService {

    @Autowired
    private YytAttrGroupMapper yytAttrGroupMapper;
    @Autowired
    private YytPmsSkuInfoMapper yytPmsSkuInfoMapper;
    @Autowired
    private YytOmsCartItemMapper yytOmsCartItemMapper;
    @Autowired
    private YytPmsSpuAttrValueMapper yytPmsSpuAttrValueMapper;
    @Autowired
    private YytPmsSkuSaleAttrValueMapper yytPmsSkuSaleAttrValueMapper;
    @Autowired
    private YytOmsOrderItemMapper yytOmsOrderItemMapper;
    @Autowired
    private YytSmsCouponHistoryService yytSmsCouponHistoryService;
    @Autowired
    private YytPmsSkuImagesService yytPmsSkuImagesService;
    
    /**
     * 根据id获取详情信息
     */
    @Override
    public YytPmsSkuInfo getInfo(String skuId) {
        YytPmsSkuInfo result = yytPmsSkuInfoMapper.getInfo(skuId);
        List<YytPmsSkuSaleAttrValue> values = yytPmsSkuSaleAttrValueMapper.listBySpuId(result.getSpuId());
        // 组装销售规格属性格式
        if (values.size() > 0) {
            String key = "key";
            Map<String, Object> item = new HashMap<>(2);
            item.put(key, values.get(0).getAttrName());
            List<YytPmsSkuSaleAttrValue> itemList = new ArrayList<>();
            for (YytPmsSkuSaleAttrValue value : values) {
                if (!item.get(key).equals(value.getAttrName())) {
                    item.put("value", itemList);
                    result.getSaleAttrValues().add(item);
                    item = new HashMap<>(2);
                    item.put(key, value.getAttrName());
                    itemList = new ArrayList<>();
                }
                itemList.add(value);
            }
            item.put("value", itemList);
            result.getSaleAttrValues().add(item);
        }
        // 根据spuId获取商品规格参数
        List<YytPmsSpuAttrValue> spuAttrValues = yytPmsSpuAttrValueMapper.listBySpuId(result.getSpuId());
        if (spuAttrValues.size() > 0) { // 没有就直接跳过
            // 遍历attrId查出attrGroup列表
            StringBuilder attrIds = new StringBuilder();
            String comma = ",";
            spuAttrValues.forEach(item -> attrIds.append(item.getAttrId()).append(comma));
            List<YytAttrGroup> yytAttrGroups = yytAttrGroupMapper.listByAttrIds(attrIds.substring(0, attrIds.length() - 1));
            // 遍历把规格参数放入对应的属性组内
            yytAttrGroups.forEach(group -> {
                Map<String, Object> map = new HashMap<>(2);
                map.put("key", group.getAttrGroupName());
                List<YytPmsSpuAttrValue> list = new ArrayList<>();

                for (int i = 0; i < spuAttrValues.size(); i++) {
                    YytPmsSpuAttrValue item = spuAttrValues.get(i);
                    // groupId是否一致 一致就放入这个组列表内
                    if (group.getAttrGroupId().equals(item.getGroupId())) {
                        list.add(item);
                        spuAttrValues.remove(i--);
                    }
                }
                map.put("value", list);

                result.getSpuAttrValues().add(map);
            });
        }
        return result;
    }

    /**
     * 根据id列表获取sku详情列表
     */
    @Override
    public List<Map<String, Object>> getInfoList(List<String> skuIdList, String memberId) {
        List<Map<String, Object>> result = new ArrayList<>();
        List<YytPmsSkuInfo> infoList = yytPmsSkuInfoMapper.getInfoList(StringUtils.join(skuIdList, ","));
        List<YytOmsCartItem> cartItems = yytOmsCartItemMapper.selectList(new QueryWrapper<YytOmsCartItem>()
                .in("product_sku_id", skuIdList).eq("member_id", memberId).orderByAsc("shop_id"));
        Map<String, Object> item = new HashMap<>(3);
        List<YytPmsSkuInfo> itemList = new ArrayList<>();
        for (YytPmsSkuInfo skuInfo : infoList) {
            YytShop shop = skuInfo.getShop();
            // 获取购买数量
            for (YytOmsCartItem cartItem : cartItems) {
                if (cartItem.getProductSkuId().equals(skuInfo.getSkuId())) {
                    skuInfo.setQuantity(cartItem.getQuantity());
                    cartItems.remove(cartItem);
                    break;
                }
            }
            List<YytSmsCoupon> userCouponSpuList = yytSmsCouponHistoryService.getUserCouponSpuList(memberId, skuInfo.getSpuInfo().getId());
            skuInfo.setCouponList(userCouponSpuList);
            skuInfo.setIsSelect(false);
            // 组装返回格式
            if (item.size() > 0 && shop.getId().equals(item.get("shopId"))) {
                itemList.add(skuInfo);
            } else {
                item = new HashMap<>(3);
                item.put("shopId", shop.getId());
                item.put("shop", shop);
                itemList = new ArrayList<>();
                itemList.add(skuInfo);
                item.put("skuList", itemList);
                result.add(item);
            }
        }
        return result;
    }

    /**
     * 获取店铺商品分页列表
     */
    @Override
    public Page<YytPmsSkuInfo> getPage(Page<YytPmsSkuInfo> page, String shopId, String searchVal) {
//        LambdaQueryWrapper<YytPmsSkuInfo> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(YytPmsSkuInfo::getShopId, shopId);
//        wrapper.orderByDesc(YytPmsSkuInfo::getSkuId);
//        if (StringUtils.isNotBlank(searchVal)) {
//            wrapper.like(YytPmsSkuInfo::getSkuName, searchVal);
//        }
//
//        return yytPmsSkuInfoMapper.getPage(page, wrapper);
        return yytPmsSkuInfoMapper.getPage(page, shopId, searchVal);
    }

    @Override
    public Boolean reduceInventory(String orderId) {
        QueryWrapper<YytOmsOrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        List<YytOmsOrderItem> yytOmsOrderItems = yytOmsOrderItemMapper.selectList(wrapper);
        for (YytOmsOrderItem yo: yytOmsOrderItems){
            yytPmsSkuInfoMapper.reduceInventory(yo.getSkuId(),yo.getSkuQuantity());
        }
        return true;
    }

    @Override
    public List<ClassBySkuInfoVo> getClassIdSkuInfo(String classId, String sortValue, String userId, Integer sqType) {
        List<ClassBySkuInfoVo> classBySkuInfo = yytPmsSkuInfoMapper.getClassBySkuInfo(classId, sortValue, userId, sqType);
        return forSkuImage(classBySkuInfo);
    }

    @Override
    public List<ClassBySkuInfoVo> getChildData(String classId, String sortValue, String userId, Integer sqType) {
        List<ClassBySkuInfoVo> childData = yytPmsSkuInfoMapper.getChildData(classId, sortValue, userId, sqType);
        return forSkuImage(childData);
    }

    @Override
    public List<YytPmsSkuInfo> getSwiperList() {
        return yytPmsSkuInfoMapper.getSwiperList();
    }


    public List<ClassBySkuInfoVo> forSkuImage(List<ClassBySkuInfoVo> list){
        List<ClassBySkuInfoVo> result = new ArrayList<>();
        for (ClassBySkuInfoVo cb : list){
            if (StringUtils.isBlank(cb.getSkuDefaultImg())){
                QueryWrapper<YytPmsSkuImages> wrapper = new QueryWrapper<>();
                wrapper.eq("sku_id", cb.getSkuId());
                List<YytPmsSkuImages> skuImages = yytPmsSkuImagesService.list(wrapper);
                cb.setSkuDefaultImg(skuImages.get(0).getImgUrl());
                cb.setSkuImg(skuImages.get(0).getImgUrl());
            }
            result.add(cb);
        }
        return result;
    }
}
